const Book = require('../../models/books');

// 获取所有书籍
exports.getAllBooks = async (req, res) => {
    try {
        // 支持通过请求体传递分页、过滤参数
        const { page = 1, limit = 10 } = req.body;
        // 查询总条数
        const total = await Book.countDocuments();
        // 查询当前页数据
        const books = await Book.find()
            .skip((page - 1) * limit)
            .limit(limit);

        // 返回包含总条数的数据结构
        res.success({
            list: books,
            total,
            page,
            limit
        }, "书籍列表获取成功");
    } catch (error) {
        res.error("获取书籍失败", 500, error.message);
    }
};

// 获取单本书籍（通过 ID）
exports.getBookById = async (req, res) => {
    try {
        const { id } = req.body; // ID 从请求体获取
        const book = await Book.findById(id);

        if (!book) {
            return res.status(404).json({ success: false, error: '书籍不存在' });
        }

        res.json({ success: true, data: book });
    } catch (error) {
        res.status(500).json({ success: false, error: error.message });
    }
};

// 创建书籍
exports.createBook = async (req, res) => {
    try {
        const { title, author, genre, publishedYear } = req.body;
        const newBook = await Book.create({
            title,
            author,
            genre,
            publishedYear
        });

        res.success(newBook, "书籍创建成功",);
    } catch (error) {
        res.error("创建书籍失败", 500, error.message);
    }
};

// 获取单本书籍
exports.getBookById = async (req, res) => {
    try {
        const book = await Book.findById(req.params.id);
        if (!book) {
            return res.notFound("书籍不存在");
        }
        res.success(book);
    } catch (error) {
        res.error("获取书籍失败", 500, error.message);
    }
};

// 更新书籍
exports.updateBook = async (req, res) => {
    try {
        const book = await Book.findByIdAndUpdate(
            req.body._id, req.body,
            { new: true, runValidators: true }
        );

        if (!book) {
            return res.notFound("书籍不存在");
        }

        res.success(book, "书籍更新成功");
    } catch (error) {
        if (error.name === "ValidationError") {
            const errors = Object.values(error.errors).map((e) => e.message);
            res.validationError(errors);
        } else {
            res.error("更新书籍失败", 500, error.message);
        }
    }
};

// 删除书籍
exports.deleteBook = async (req, res) => {
    try {
        const book = await Book.findByIdAndDelete(req.query.id);
        if (!book) {
            return res.notFound("书籍不存在");
        }
        res.success(null, "书籍删除成功");
    } catch (error) {
        res.error("删除书籍失败", 500, error.message);
    }
};

exports.searchBooks = async (req, res) => {
    try {
        const { keyword, genre, page = 1, limit = 10 } = req.body;
        const query = {};

        if (keyword) {
            query.title = { $regex: keyword, $options: 'i' };
        }
        if (genre) {
            query.genre = genre;
        }

        // 分页查询
        const books = await Book.find(query)
            .skip((page - 1) * limit)
            .limit(limit);

        const total = await Book.countDocuments(query); // 总条数

        res.success({
            list: books,
            total,
            page,
            limit
        }, "书籍搜索成功");
    } catch (error) {
        res.error("搜索失败", 500, error.message);
    }
};

